package structure.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lzp
 * @Date:2023/2/27
 * @description: 具有缓存功能的学生类
 */
public class Student {


	/**
	 * 提供一个学生缓存，同名的学生直接返回
	 */
	private static final Map<String, Student> cache = new HashMap<String, Student>();

	/**
	 * 暴露一个学生创建接口，用于创建可复用的学生
	 */
	public static Student crete(String name, Integer id) {
		String key = id + "\n" + name;
		// 先查找缓存:
		Student student = cache.get(key);
		if (student == null) {
			// 未找到,创建新对象:
			student = new Student(name, id);
			// 放入缓存:
			cache.put(key, student);
		}
		return student;
	}

	private String name;
	private Integer id;

	public Student(String name, Integer id) {
		this.name = name;
		this.id = id;
	}

}
